/**
 * 
 */
package com.huangliusong;

import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.event.MenuEvent;
import javax.swing.event.MenuListener;

/**
 * @author huangliusong E-mail:huangliusong1994@gmail.com
 * @version 创建时间：2018年7月16日 下午3:28:08 类说明
 */
public class FileFrame {
	static List<Map<String, Object>> listAllFile;
	static List<Map<String, Object>> listNewFile;
	static String path = "";
	@SuppressWarnings("rawtypes")
	JList list;

	public static void main(String[] args) {
		new FileFrame().exeMonitor();
	}

	@SuppressWarnings("static-access")
	public void exeMonitor() {
		path = JOptionPane.showInputDialog("请输监控路径");
		if (path == null) {
			JOptionPane.showMessageDialog(new JFrame().getContentPane(),
					"您选择退出！", "系统信息", JOptionPane.ERROR_MESSAGE);
			System.exit(3);
		} else {
			if (path.equals("") || path.equals(null)) {
				JOptionPane.showMessageDialog(new JFrame().getContentPane(),
						"路径名不能为空", "系统信息", JOptionPane.WARNING_MESSAGE);
				System.exit(3);
			} else {
				new FileFrame().getAllData();
				new FileFrame().mainJframe();
			}
		}
	}

	public static List<Map<String, Object>> getAllData() {
		listAllFile = new ArrayList<>();
		List<String> list = ReadDirectory.getAllFile(path, true);
		for (int i = 0; i < list.size(); i++) {
			Map<String, Object> map = new HashMap<>();
			File file = new File(list.get(i));
			long time = file.lastModified();
			String ctime = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss")
					.format(new Date(time));
			String filePath = list.get(i);
			map.put("filepath", filePath);
			map.put("createtime", ctime);
			listAllFile.add(map);
		}
		return listAllFile;

	}

	public static List<Map<String, Object>> getNewData() {
		listNewFile = new ArrayList<>();
		List<String> list = ReadDirectory.getAllFile(path, true);
		for (int i = 0; i < list.size(); i++) {
			Map<String, Object> map = new HashMap<>();
			File file = new File(list.get(i));
			long time = file.lastModified();
			String ctime = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss")
					.format(new Date(time));
			String filePath = list.get(i);
			map.put("filepath", filePath);
			map.put("createtime", ctime);
			listNewFile.add(map);
		}
		return listNewFile;

	}

	public static void setSysClipboardText(String writeMe) {
		Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard();
		Transferable tText = new StringSelection(writeMe);
		clip.setContents(tText, null);
	}

	@SuppressWarnings("rawtypes")
	public void mainJframe() {
		JFrame a = new JFrame("文件监控LDM v1.1");// 顶层容器
		ImageIcon icon = new ImageIcon("ldm.png"); // 图片和项目同一路径，故不用图片的路径
		a.setIconImage(icon.getImage());
		JMenuBar jmb = new JMenuBar();
		JMenu jMenu = new JMenu("同步文件");
		// 添加事件监听器(此处即为匿名类)
		jMenu.addMenuListener(new MenuListener() {

			@SuppressWarnings("unchecked")
			@Override
			public void menuSelected(MenuEvent e) {
				DefaultListModel listModel = new DefaultListModel();
				listAllFile = getAllData();
				list.setModel(listModel);
			}

			@Override
			public void menuDeselected(MenuEvent e) {

			}

			@Override
			public void menuCanceled(MenuEvent e) {

			}
		});
		list = new JList();
		test1Model(list, listNewFile);

		list.setBorder(BorderFactory.createTitledBorder("文件列表"));

		list.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {

				if (list.getSelectedIndex() != -1) {
					if (e.getClickCount() == 1) {
						String str = list.getSelectedValue().toString();
						String pathString = str.split("------------------")[0];
						setSysClipboardText(pathString);
					} else if (e.getClickCount() == 2) {
						String str = list.getSelectedValue().toString();
						String pathString = str.split("------------------")[0];
						try {
							java.awt.Desktop.getDesktop().open(
									new File(pathString));
						} catch (Exception e2) {
							System.err.println("文件不存在");
							JOptionPane.showMessageDialog(null,
									"" + e2.getMessage(), "监控提示",
									JOptionPane.ERROR_MESSAGE);
						}

					} else {
						System.err.println("其他操作");
						JOptionPane.showMessageDialog(null, "文件路径已经复制到剪切板");
					}
				}
			};
		});

		a.add(new JScrollPane());
		jmb.add(jMenu);

		a.setJMenuBar(jmb); // 添加菜单栏，不能设定位置，会自动放在最上部
		JScrollPane sp = new JScrollPane(list);
		a.getContentPane().add(sp);
		a.setBounds(260, 100, 488, 608);
		a.setVisible(true);
		a.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		a.setDefaultCloseOperation(3);
	}

	@SuppressWarnings("rawtypes")
	public static void test1Model(JList jlist,
			List<Map<String, Object>> listNewFile) {
		// 单位: 毫秒
		final long timeInterval = 1000;
		Runnable runnable = new Runnable() {
			@SuppressWarnings("unchecked")
			public void run() {
				while (true) {
					List<Map<String, Object>> listAllFile_ = listAllFile;
					List<Map<String, Object>> listNewFile_ = FileFrame
							.getNewData();
					List<Map<String, Object>> listAllFile__ = new ArrayList<>();
					if (listAllFile_.size() == listNewFile_.size()) {
						System.err.println("沒有新增文件！");
					} else {
						// 遍历查找新增的文件
						for (int i = 0; i < listNewFile_.size(); i++) {
							String filepath = (String) listNewFile_.get(i).get(
									"filepath");
							String createtime = (String) listNewFile_.get(i)
									.get("createtime");
							if (JudgeExist.existValue(listAllFile_, filepath)) {
								Map<String, Object> map = new HashMap<>();
								map.put("filepath", filepath);
								map.put("createtime", createtime);
								listAllFile__.add(map);
							}

						}
						// 将新增文件添加到界面
						DefaultListModel listModel = new DefaultListModel();
						for (int i = 0; i < listAllFile__.size(); i++) {
							String filepath = listAllFile__.get(i)
									.get("filepath").toString();
							String createtime = listAllFile__.get(i)
									.get("createtime").toString();
							listModel.addElement(filepath
									+ "------------------" + createtime);
						}
						jlist.setModel(listModel);
					}
					try {
						System.err.println("...");
						Thread.sleep(timeInterval);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		};
		Thread thread = new Thread(runnable);
		thread.start();
	}
}
